﻿using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace OneByOne
{
    internal static class SystemConsole
    {
        public delegate bool Check<T>(string strValue, [NotNullWhen(true)] out T? value);

        public static T ReadAndCheck<T>(string message, Check<T> check)
        {
            Console.WriteLine(message);
            for (; ; )
            {
                var str = Console.ReadLine();
                Debug.Assert(str is not null);
                if (check(str, out var value))
                    return value;
                Console.WriteLine("输入有误，请重新输入：");
            }
        }
        public static int ReadAndCheckInt(string message)
        {
            Check<int> check = int.TryParse;
            return ReadAndCheck(message, check);
        }
        public static int ReadAndCheckPositiveInt(string message)
        {
            bool Check(string strValue, out int value)
            {
                if (int.TryParse(strValue, out value) && value > 0)
                {
                    return true;
                }
                return false;
            }

            Check<int> check = Check;
            return ReadAndCheck(message, check);
        }
        public static bool ReadAndCheckYesOrNo(string message)
        {
            bool Check(string strValue, out bool value)
            {
                var lower = strValue.ToLower();
                if (lower is "y" or "yes")
                {
                    value = true;
                    return true;
                }
                value = false;
                return lower is "n" or "no";
            }

            Check<bool> check = Check;
            return ReadAndCheck(message, check);
        }
    }
}
